package com.stony.core.struts.action;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.config.ExceptionConfig;

import com.stony.core.exception.RunException;

/**
 * <p>
 * An <strong>ExceptionHandler</strong> is configured in the Struts
 * configuration file to handle a specific type of exception thrown by an
 * <code>Action.execute</code> method.
 * </p>
 * 
 * @since Struts 1.1
 */
public class ExceptionHandler extends org.apache.struts.action.ExceptionHandler {

	public ActionForward execute(Exception ex, ExceptionConfig ae,
			ActionMapping mapping, ActionForm formInstance,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException {

		ActionForward forward = null;
		ActionMessage error = null;
		String property = null;

		// Build the forward from the exception mapping if it exists
		// or from the form input
		if (ae.getPath() != null) {
			forward = new ActionForward(ae.getPath());
		} else {
			forward = mapping.getInputForward();
		}

		// Figure out the error
		if (ex instanceof RunException) {
			error = new ActionMessage(ex.getMessage(), ((RunException) ex)
					.getValues());
			property = ((RunException) ex).getProperty();
			if (property == null)
				property = ActionMessages.GLOBAL_MESSAGE;
		} else {
			error = new ActionMessage(ae.getKey(), ex.getMessage());
			property = error.getKey();
		}

		this.logException(ex);

		ex.printStackTrace();
		
		// Store the exception
		request.setAttribute(Globals.EXCEPTION_KEY, ex);
		this.storeException(request, property, error, forward, ae.getScope());

		return forward;

	}

}
